﻿using System.Collections.Generic;
using System.Text;

namespace Com.ZGH.Dns
{
    public class DnsName :IElement
    {
        private string query;
        private int size;

        public DnsName()
        {
        }

        public DnsName(string query)
        {
            this.query = query;
        }

        public string Query
        {
            get { return query; }
            set { query = value; }
        }

        public int Size
        {
            get { return size > 0 ? size : query.Length + 2; }
        }

        public byte[] ToBytes()
        {
            var d1 = 0;
            var d2 = 0;
            var bytes = new List<byte>(512);

            while (d2 < query.Length)
            {
                if (query[d2] == '.')
                {
                    bytes.Insert(d1, (byte) (d2 - d1));
                    d1 = ++d2;
                }
                else
                {
                    bytes.Add((byte) query[d2++]);
                }
            }
            bytes.Insert(d1, (byte)(d2 - d1));
            bytes.Add(0);

            return bytes.ToArray();
        }

        public static DnsName Parse(byte[] value,int start)
        {
            var dnsName = new DnsName();
        
            var stringBuilder=new StringBuilder();

            var end=ReadPointer(value, start, stringBuilder);

            dnsName.query = stringBuilder.ToString();

            dnsName.size = end - start;

            return dnsName;
        }

        protected static int ReadPointer(byte[] value,int start,StringBuilder stringBuilder)
        {
            var d1 = value[start];
            var index = start + 1;
   
            while (d1 > 0)
            {
                //指针形式的名字
                if(d1==0xC0)
                {
                    ReadPointer(value,value[index],stringBuilder);
                    index++;
                    break;
                }
                else
                {
                    stringBuilder.Append((char)value[index++]);

                    if (--d1 == 0)
                    {
                        d1 = value[index++];
                        if (d1 > 0) stringBuilder.Append('.');
                    }
                }

            }

            return index;
        }
    }
}
